package com.lyon.demo.rpc.naming.context;

import com.lyon.demo.rpc.api.core.ServiceInstance;
import com.lyon.demo.rpc.api.core.ServiceInstances;
import io.netty.channel.Channel;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author LeeYan9
 * @since 2022-04-15
 */
public class ServiceContextHolder {

    private static Map<String, ServiceInstances> serviceInstanceMap= new ConcurrentHashMap<>();

    private static Map<String, String> interfaceMap = new ConcurrentHashMap<>();


    private static Map<ServiceInstances, Channel> channelMap = new ConcurrentHashMap<>();

    public static void addService(ServiceInstance serviceInstance) {
        final String serviceName = serviceInstance.getServiceName();
        ServiceInstances serviceInstances = serviceInstanceMap.get(serviceName);
        if (Objects.isNull(serviceInstances)) {
            serviceInstanceMap.put(serviceName,new ServiceInstances());
            serviceInstances = serviceInstanceMap.get(serviceName);;
            serviceInstances.setServiceName(serviceInstance.getServiceName());
        }
        serviceInstances.addInstance(serviceInstance);
    }

    public static ServiceInstances getService(String serviceName) {
        return serviceInstanceMap.get(serviceName);
    }

    public static ServiceInstances getServiceByInterface(String interfaceName) {
        final String serviceName = interfaceMap.get(interfaceName);
        if (Objects.isNull(serviceName)) {
            return null;
        }
        return serviceInstanceMap.get(serviceName);
    }

    public static void addChannel(ServiceInstances serviceInstances, Channel channel) {
        channelMap.put(serviceInstances,channel);
    }

    public static Channel getChannel(ServiceInstances serviceInstances) {
        return channelMap.get(serviceInstances);
    }

    public static ServiceInstances get(String serviceName) {
        return serviceInstanceMap.get(serviceName);
    }

    public static void addInterface(String interfaceName, String serviceName) {
        interfaceMap.put(interfaceName,serviceName);
    }
}
